package com.littcore.saap.system.web;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.chanjar.weixin.mp.bean.result.WxMpPrepayIdResult;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.littcore.common.Utility;
import com.littcore.saap.core.web.util.LoginUtils;
import com.littcore.saap.matrix.MatrixToImageWriter;
import com.littcore.saas.wechat.service.IWechatPayService;


@Controller
public class WechatPayController {

    
    @Resource
    private IWechatPayService wechatPayRemote;
    
    @RequestMapping
    public ModelAndView pay(@RequestParam String orderNo,HttpServletRequest request,ModelMap model){
        Double orderFee=Utility.parseDouble(request.getParameter("orderFee"));
        String productId=request.getParameter("productId");
       return new ModelAndView("/system/wechatPay/pay").addObject("orderNo", orderNo).addObject("orderFee",orderFee).addObject("productId",productId);
    }
    
    
    
    @RequestMapping
    public ModelAndView payCode(HttpServletRequest request,HttpServletResponse response){
        String orderNo=request.getParameter("orderNo");
        Double orderFee=Utility.parseDouble(request.getParameter("orderFee"));
        String productId=request.getParameter("productId");
        String callbackurl="http://cp.littcore.com/pay/callback";
        WxMpPrepayIdResult result= wechatPayRemote.getNativePrepayUrl(productId,orderNo, orderFee, "套餐", LoginUtils.getLoginIp(), callbackurl);
        
       try {
           
           MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
           
           Map hints = new HashMap();
           hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
           BitMatrix bitMatrix = multiFormatWriter.encode(result.getCode_url(), BarcodeFormat.QR_CODE, 400, 400,hints);
           BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);          
           ImageIO.write(image, "jpg", response.getOutputStream());
           
       } catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
       }
        
        return null;
    }

}
